package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;


@RestController
@RequestMapping("/user")
public class UserController {
    //获得当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername() {
        //当spring-security完成认证后,会将当前用户信息保存到框架提供的上下文对象中
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user != null) {
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, username);
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }



        @RequestMapping("/getPassword")
        public Result getPassword() {
            //当spring-security完成认证后,会将当前用户信息保存到框架提供的上下文对象中
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (user != null) {
                String password = user.getPassword();
                return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, password);
            }
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }

        @RequestMapping(value = "/say",produces ="application/json;charset=utf-8")
        @ResponseBody
        public ModelAndView say(ModelAndView modelAndView, HttpServletResponse response, HttpServletRequest request){
            try {
                request.setCharacterEncoding("utf-8");
                response.setContentType("text/javascript;charset=utf-8");
            }catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
            modelAndView.setViewName("redirect:/login.html");
            modelAndView.addObject("error","账号或密码错误");
            return modelAndView;
        }
    }
